package com.tgy.admin.Service.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.tgy.admin.Service.MenuService;
import com.tgy.admin.Service.RoleService;
import com.tgy.admin.util.BeanFieldUtils;
import com.tgy.core.service.SysAdminRoleService;
import com.tgy.core.service.SysPermissionService;
import com.tgy.core.service.SysRolePermissionService;
import com.tgy.core.service.SysRoleService;
import com.tgy.dTree.Dtree;
import com.tgy.dTree.Status;
import com.tgy.dTree.TreeNode;
import com.tgy.enums.ResponseStatusEnum;
import com.tgy.enums.YesOrNo;
import com.tgy.exception.GlobalException;
import com.tgy.exception.ResultException;
import com.tgy.page.PageQuery;
import com.tgy.pojo.SysPermission;
import com.tgy.pojo.SysRole;
import com.tgy.pojo.SysRolePermission;
import com.tgy.result.GraceJSONResult;
import com.tgy.result.LayuiTableResult;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author tianguiyin
 * @version 1.0
 * @date 2022/6/21 21:04
 *
 * 后台用户业务实现
 */
@Service
public class RoleServiceImpl implements RoleService {

    @Resource
    private SysRoleService sysRoleService;
    @Resource
    private SysAdminRoleService sysAdminRoleService;
    @Resource
    private SysRolePermissionService sysRolePermissionService;
    @Resource
    private SysPermissionService sysPermissionService;
    @Resource
    private MenuService menuService;
    @Resource
    private BeanFieldUtils beanFieldUtils;

    @Override
    public LayuiTableResult getSysRoleList(SysRole bo,PageQuery pageQuery) {
        // bo.setAvailable(-1);
        return sysRoleService.queryLayuiPageList(bo,pageQuery);
    }

    @Override
    public GraceJSONResult updateStatus(String id, Integer status) {
        int i = sysRoleService.updateStatus(id,status);
        if (i>0){
            return GraceJSONResult.ok();
        }else {
            return GraceJSONResult.error();
        }
    }

    @Override
    public GraceJSONResult addSysRole(SysRole sysRole) {
        try {
            // 角色名不能重复
            Integer available = sysRole.getAvailable();
            sysRole.setAvailable(null);
            List<SysRole> sysRoles = sysRoleService.queryList(sysRole,false);
            if (CollectionUtil.isNotEmpty(sysRoles)){
                return GraceJSONResult.error("角色名不能重复");
            }
            sysRole.setAvailable(available);
            beanFieldUtils.add(sysRole);
            Boolean aBoolean = sysRoleService.insertByBo(sysRole);
            return GraceJSONResult.ok(ResponseStatusEnum.ADD_SUCCESS);
        }catch (Exception e){
            if (e instanceof ResultException){
                ResultException e1 = (ResultException) e;
                return e1.getGraceJSONResult();
            }else {
                e.printStackTrace();
                return GraceJSONResult.error(ResponseStatusEnum.ADD_ERROR);
            }
        }
    }

    @Override
    public GraceJSONResult updateSysRole(SysRole sysRole) {
        try {
            // 角色名不能重复
            List<SysRole> sysRoles = sysRoleService.queryList(sysRole,false);
            if (CollectionUtil.isNotEmpty(sysRoles) && !sysRoles.get(0).getId().equals(sysRole.getId())){
                return GraceJSONResult.error("角色名不能重复");
            }
            SysRole SysRole1 = sysRoleService.queryById(sysRole.getId());
            // String createdBy = SysRole1.getCreatedBy();
            // LocalDateTime createdTime = SysRole1.getCreatedTime();
            BeanUtil.copyProperties(sysRole,SysRole1);
            beanFieldUtils.update(SysRole1);
            // SysRole1.setCreatedBy(createdBy);
            // SysRole1.setCreatedTime(createdTime);
            Boolean aBoolean = sysRoleService.updateByBo(SysRole1);
            return GraceJSONResult.ok(ResponseStatusEnum.UPDATE_SUCESS);
        }catch (Exception e){
            e.printStackTrace();
            return GraceJSONResult.error(ResponseStatusEnum.UPDATE_ERROR);
        }
    }

    @Transactional
    @Override
    public GraceJSONResult delSysRole(String id) {
        try {
            Boolean aBoolean = sysRoleService.deleteById(id);
            // 删除用户关联信息
            List<String> list = new ArrayList<>();
            list.add(id);
            sysAdminRoleService.deleteByRid(list);
            // 删除权限关联信息
            sysRolePermissionService.deleteByRid(list);
            return GraceJSONResult.ok(ResponseStatusEnum.DDELETE_SUCESS);
        }catch (Exception e){
            e.printStackTrace();
            return GraceJSONResult.error(ResponseStatusEnum.DDELETE_ERROR);
        }
    }

    @Transactional
    @Override
    public GraceJSONResult delSysRoleIds(List<String> ids) {
        try {
            Boolean aBoolean = sysRoleService.deleteWithValidByIds(ids,false);
            // 删除用户关联信息
            sysAdminRoleService.deleteByRid(ids);
            // 删除权限关联信息
            sysRolePermissionService.deleteByRid(ids);
            return GraceJSONResult.ok(ResponseStatusEnum.DDELETE_SUCESS);
        }catch (Exception e){
            e.printStackTrace();
            return GraceJSONResult.error(ResponseStatusEnum.DDELETE_ERROR);
        }
    }

    @Override
    public GraceJSONResult getSysRoleById(String id) {
        return GraceJSONResult.ok(sysRoleService.queryById(id));
    }

    @Override
    public Dtree getSysRolePermission(String rid) {
        // 查询所有状态为启用的权限数据
        SysPermission permission = new SysPermission();
        permission.setAvailable(YesOrNo.YES.type);
        List<SysPermission> permissions = sysPermissionService.queryList(permission);

        // 查询角色已经拥有的权限信息
        SysRolePermission rolePermission = new SysRolePermission();
        rolePermission.setRid(rid);
        List<SysRolePermission> rolePermissions = sysRolePermissionService.queryList(rolePermission);
        List<String> rolePermissionIds = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(rolePermissions)){
            rolePermissionIds = rolePermissions.stream().map(SysRolePermission::getPid).collect(Collectors.toList());
        }

        List<TreeNode> data = new ArrayList<>();
        for (SysPermission sysPermission : permissions) {
            TreeNode treeNode = new TreeNode();
            BeanUtil.copyProperties(sysPermission,treeNode);
            Integer open = sysPermission.getOpen();
            if (Objects.nonNull(open) && open.equals(YesOrNo.NO.type)){
                treeNode.setSpread(false);
            }
            if (rolePermissionIds.contains(sysPermission.getId())){
                treeNode.setCheckArr(YesOrNo.YES.type.toString());
            }
            data.add(treeNode);
        }

        return new Dtree(new Status(),data);
    }

    @Transactional
    @Override
    public GraceJSONResult addSysRolePermission(String rid, String pids) {
        if (StrUtil.isBlank(rid)){
            GlobalException.display(GraceJSONResult.error("角色ID不能为空"));
        }
        // 删除之前的权限
        List<String> rids = new ArrayList<>();
        rids.add(rid);
        sysRolePermissionService.deleteByRid(rids);

        //添加新的信息
        List<String> list = new ArrayList<>(Arrays.asList(pids.split(",")));
        List<SysRolePermission> rolePermissions = new ArrayList<>();
        for (String pid : list) {
            SysRolePermission rolePermission = new SysRolePermission();
            rolePermission.setRid(rid);
            rolePermission.setPid(pid);
            rolePermissions.add(rolePermission);
        }
        sysRolePermissionService.insertByList(rolePermissions);

        String loginId = StpUtil.getLoginId().toString();
        // 更新权限相关信息
        new Thread(){
            @Override
            public void run() {
                menuService.getMenuAndRoleAndPermission(loginId);
            }
        }.start();

        return GraceJSONResult.ok();
    }
}
